package com.hospital.doctor.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.hospital.doctor.pojo.Medical;
import com.hospital.doctor.pojo.Patient;
import com.hospital.doctor.service.MedicalService;
import com.hospital.doctor.service.PatientService;
import com.hospital.doctor.utils.JWTUtils;
import com.hospital.doctor.utils.NoEmpty;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/medical")
@CrossOrigin
public class MedicalController {

    @Autowired
    private MedicalService medicalService;

    @Autowired
    private PatientService patientService;


    /**
     * 根据患者id查询
     * @param id
     * @return
     */
    @RequestMapping("/selectById/{id}")
    public Map<String,Object> selectById(@PathVariable("id") int id){
        List<Medical> medicals = medicalService.selectById(id);
        Map<String, Object> map = new HashMap<>();
        map.put("msg",medicals);
        return map;
    }

    /**
     * 根据mid查询医嘱
     * @param mId
     * @return
     */
    @RequestMapping("/selectBymId/{mId}")
    public Medical  selectBymId(@PathVariable("mId") int mId){
        return medicalService.selectBymId(mId);
    }

    /**
     * 添加医嘱
     * @param medical
     * @param request
     * @return
     */
    @RequestMapping("/insertMedical")
    public Map<String,Object> insertMedical(@RequestBody Medical medical, HttpServletRequest request){
        Map<String,Object> map = new HashMap<>();
        Date startTime = medical.getmStartTime();
        Date EndTime = medical.getmEndTime();
        Date exeTime = medical.getmExeTime();
        String status1 = medical.getmStatus();
        String status = medical.getmStatus().replaceAll("\\s*", "");
        String content = medical.getmContent().replaceAll("\\s*","");
        String token = request.getHeader("token");
        DecodedJWT verify = JWTUtils.verify(token);
        Integer id = Integer.valueOf(verify.getClaim("id").asString());
        medical.setdId(id);

        if (status==null||status.equals("")){
            map.put("msg","请选中医嘱类型");
            return map;
        }
        if (content==null||content.equals("")){
            map.put("msg","请输入医嘱内容");
            return map;
        }
        if (startTime==null){
            map.put("msg","开始时间不能为空");
            return map;
        }
        if (exeTime==null){
            map.put("msg","执行时间不能为空");
            return map;
        }
        if (EndTime==null){
            map.put("msg","结束时间不能为空");
            return map;
        }
        if (startTime!=null && EndTime!=null){
            Integer endTime1 = new Long(EndTime.getTime()/1000).intValue();
            Integer startTime1 = new Long(startTime.getTime()/1000).intValue();
            if (endTime1<startTime1){
                map.put("msg","请正确选中时间节点");
                return map;
            }

        }
        map.put("msg",medicalService.insertMedical(medical));
        return map;
    }

    @RequestMapping("/updateMedical")
    public Map<String,Object> updateMedical(@RequestBody Medical medical){
        Map<String,Object> map = new HashMap<>();
        int i = medicalService.updateMedical(medical);
        map.put("msg",i);
        return map;
    }

    //遍历所有的医嘱信息并获取病人信息
    @RequestMapping("/getMedicalAndPatient/{id}")
    public Map<String,Object> getMedicalAndPatient(@PathVariable("id") int id){
        Map<String,Object> map = new HashMap<>();
        map.put("medical",medicalService.selectById(id));
        map.put("patient",patientService.selectById(id));
        return map;
    }

    //停止医嘱
    @RequestMapping("/stopMedical/{id}")
    public Map<String,Object> stopMedical(@PathVariable("id") int id){
        Map<String,Object> map = new HashMap<>();
        map.put("stop",medicalService.stopMedical(id));
        return map;
    }


    //导出excel
    @RequestMapping("/download/{pId}/{pName}")
    public void upload(HttpServletResponse response,@PathVariable("pId") int pId,@PathVariable("pName") String pName) throws IOException {
        System.out.println(pId);
        System.out.println(pName);
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode(pName+"医嘱", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(),Medical.class).sheet("医嘱")
                    .doWrite(medicalService.selectById(pId));
            System.out.println("+++++++++++");
        } catch (Exception e) {
            System.out.println("============");
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }


}
